package cn.finder0519.simplemediaplayer;

import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ServiceInfo;
import android.media.AudioManager;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.media3.common.AudioAttributes;
import androidx.media3.common.C;
import androidx.media3.exoplayer.ExoPlayer;

public class PlaybackService extends Service {

    public static final int NOTIFICATION_ID = 1;
    public static final String ACTION_PLAY = "cn.finder0519.simplemediaplayer.ACTION_PLAY";
    public static final String ACTION_PAUSE = "cn.finder0519.simplemediaplayer.ACTION_PAUSE";
    public static final String ACTION_TOGGLE_LOOP = "cn.finder0519.simplemediaplayer.ACTION_TOGGLE_LOOP";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        ExoPlayer player = PlayerManager.getPlayer(); // 我假设你有PlayerManager来拿到player

        if (intent != null && intent.getAction() != null && player != null) {
            String action = intent.getAction();
            if (ACTION_PLAY.equals(action)) {
                player.play(); // 再开始播放
            } else if (ACTION_PAUSE.equals(action)) {
                player.pause();
            } else if (ACTION_TOGGLE_LOOP.equals(action)) {
                int currentRepeatMode = player.getRepeatMode();
                if (currentRepeatMode == ExoPlayer.REPEAT_MODE_ONE) {
                    player.setRepeatMode(ExoPlayer.REPEAT_MODE_OFF);
                } else {
                    player.setRepeatMode(ExoPlayer.REPEAT_MODE_ONE);
                }
            }
            player.setAudioAttributes(
                    new AudioAttributes.Builder()
                            .setUsage(C.USAGE_MEDIA)
                            .setContentType(C.AUDIO_CONTENT_TYPE_MOVIE)
                            .build(),
                    false // 不处理音频焦点变化
            );
        }

        // 更新通知（根据当前播放状态 & 循环状态）
        boolean isPlaying = player != null && player.isPlaying();
        boolean isLooping = player != null && player.getRepeatMode() == ExoPlayer.REPEAT_MODE_ONE;
        // 构建通知（你已有 NotificationHelper 类）
        Notification notification = NotificationHelper.buildPlaybackNotification(this, isPlaying, isLooping);
        // 设置为前台服务
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
            startForeground(NOTIFICATION_ID, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PLAYBACK);
        } else {
            startForeground(NOTIFICATION_ID, notification);
        }

        return START_STICKY; // 保持服务，除非系统主动杀掉
    }

    private final BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ExoPlayer player = PlayerManager.getPlayer();
            if (player != null && player.isPlaying()) {
                // 忽略系统默认暂停，继续播放
                Log.d("PlaybackService", "AUDIO_BECOMING_NOISY received, but ignoring pause");
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        registerReceiver(becomingNoisyReceiver, new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(becomingNoisyReceiver);
        stopForeground(true); // 移除通知
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
